package net.vinote.smart.platform.controller;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

import javax.imageio.ImageIO;

import net.vinote.smart.platform.comm.StringFunction;
import net.vinote.smart.platform.service.SRE;

import org.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;

/**
 * 二维码Controller类
 * 
 * @author Seer
 * @version QRCodeController.java, v 0.1 2015年3月24日 上午9:36:05 Seer Exp.
 */
@Controller
public class QRCodeController {
	@RequestMapping("todayAttendance.html")
	public String showTodayAttendance() {
		return "todayAttendance";
	}

	@RequestMapping("todayAttendance.seer")
	public void getTodayAttendance(OutputStream out) {
		JSONObject json = new JSONObject();
		json.put("date", StringFunction.getTime());
		// flushQRCode(json, "jpg", 400, 400, out);
		flushQRCode(SRE.getSystemParameter().getDomain()
				+ "/addTodayAttendance.html", "jpg", 400, 400, out);
	}

	private static final int BLACK = 0xFF000000;

	private static final int WHITE = 0xFFFFFFFF;

	private void flushQRCode(JSONObject json, String format, int width,
			int height, OutputStream out) {
		flushQRCode(json.toString(), format, width, height, out);
	}

	private void flushQRCode(String content, String format, int width,
			int height, OutputStream out) {

		MultiFormatWriter multiFormatWriter = new MultiFormatWriter();

		Map hints = new HashMap();
		hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
		hints.put(EncodeHintType.MARGIN, 0);
		BitMatrix bitMatrix;
		try {
			bitMatrix = multiFormatWriter.encode(content,
					BarcodeFormat.QR_CODE, width, height, hints);
			writeToStream(bitMatrix, "jpg", out);
		} catch (WriterException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	private BufferedImage toBufferedImage(BitMatrix matrix) {
		int width = matrix.getWidth();
		int height = matrix.getHeight();
		BufferedImage image = new BufferedImage(width, height,
				BufferedImage.TYPE_INT_RGB);
		for (int x = 0; x < width; x++) {
			for (int y = 0; y < height; y++) {
				image.setRGB(x, y, matrix.get(x, y) ? BLACK : WHITE);
			}
		}
		return image;
	}

	private void writeToStream(BitMatrix matrix, String format,
			OutputStream stream) throws IOException {
		BufferedImage image = toBufferedImage(matrix);
		if (!ImageIO.write(image, format, stream)) {
			throw new IOException("Could not write an image of format "
					+ format);
		}
	}
}
